﻿using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Components;
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using TrackSystem.Contracts;
using TrackSystem.Entities.Dtos.Sensor;
using TrackSystem.UI.Server.HttpRepository.Sensor;

namespace TrackSystem.UI.Server.Components.Elements
{
    public partial class SensorCard
    {
        [Parameter]
        public int Id { get; set; }

        /// <summary>
        /// 传感器列表数据源
        /// </summary>
        private IEnumerable<SensorWithChannelDto?>? sensors = Enumerable.Empty<SensorWithChannelDto>();

        [Inject]
        public ISensorHttpRepository? repo { get; set; }

        [Inject]
        [NotNull]
        private ToastService? ToastService { get; set; }

        /// <summary>
        /// 修改状态字典，用于跟踪每个传感器的修改状态
        /// </summary>
        private ConcurrentDictionary<int, bool> changedStatus = new();

        /// <summary>
        /// 插入新数据模式
        /// </summary>
        private bool IsInsertMode { get; set; } = false;
        private SensorWithChannelDto? sensorForInsert = null;

        /// <summary>
        /// OnInitializedAsync 方法在组件初始化时调用
        /// </summary>
        /// <returns></returns>
        protected override async Task OnInitializedAsync()
        {
            try
            {
                if (repo == null)
                {
                    await ToastService.Error("传感器列表", "数据库未初始化");
                    return;
                }

                if (Id == 0 )
                    sensors = await repo.GetAll();
                else
                {
                     var snr = await repo.GetSingleSensor(Id);
                     sensors = [snr.Data,];
                }

                foreach (var sensor in sensors)
                {
                    if (sensor != null)
                    {
                        changedStatus.TryAdd(sensor.Id, false);
                    }
                }
            }
            catch (Exception ex)
            {
                await ToastService.Error("传感器列表", ex.Message);
            }
        }

        /// <summary>
        /// OnPageClick 方法用于处理分页点击事件
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        private async Task OnPageClick(int pageIndex)
        {
        }

        /// <summary>
        /// OnDeleted 方法用于处理传感器删除事件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private async Task OnDeleted(int id)
        {
            if (repo == null)
            {
                await ToastService.Error("传感器列表", "数据库未初始化");
                return;
            }
            if (sensors == null || !sensors.Any())
            {
                await ToastService.Error("传感器列表", "没有可删除的传感器");
                return;
            }

            var result = await repo.DeleteAsync(id);
            if (!result.Success)
            {
                await ToastService.Error("传感器删除", result.Message);
                return;
            }

            await ToastService.Success("传感器删除", "数据删除成功");
            sensors = await repo.GetAll();
            StateHasChanged();
        }

        /// <summary>
        /// OnStartInsert 方法用于开始插入新传感器数据
        /// </summary>
        /// <returns></returns>
        private async Task OnStartInsert()
        {
            IsInsertMode = true;
            sensorForInsert = new SensorWithChannelDto
            {
                Name = "新传感器",
                channelID = sensors.First().channelID,
                RO_Address = 0,
                RO_Length = 0,
                RW_Address = 0,
                RW_Length = 0,
                Station = 1 // 默认站地址
            };
        }

        /// <summary>
        /// OnFinishInsert 方法用于完成插入新传感器数据
        /// </summary>
        /// <returns></returns>
        private async Task OnFinishInsert()
        {
            if (repo == null)
            {
                await ToastService.Error("传感器列表", "数据库未初始化");
                return;
            }
            if (sensorForInsert == null)
            {
                await ToastService.Error("传感器列表", "传感器数据未准备好");
                return;
            }
            var result = await repo.InsertAsync(sensorForInsert);
            if (!result.Success)
            {
                await ToastService.Error("传感器添加", result.Message);
                sensors = await repo.GetAll();
                StateHasChanged();
            }
            else
            {
                await ToastService.Success("传感器添加", "数据添加成功");
                IsInsertMode = false;
                sensorForInsert = null;
                sensors = await repo.GetAll();
                StateHasChanged();
            }
            IsInsertMode = false; // Reset insert mode
        }

        /// <summary>
        /// OnStartChange 方法用于开始修改传感器数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private async Task OnStartChange(int id)
        {
            if (changedStatus.TryGetValue(id, out var status))
            {
                changedStatus[id] = true;
            }
        }

        /// <summary>
        /// OnChangedCancel 方法用于取消修改传感器数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private async Task OnChangedCancel(int id)
        {
            if (changedStatus.TryGetValue(id, out var status))
            {
                changedStatus[id] = false; // Reset the status to not changed
                sensors = await repo.GetAll();
                StateHasChanged();
            }
        }

        /// <summary>
        /// OnChanged 方法用于处理传感器数据的修改
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private async Task OnChanged(int id)
        {
            if (changedStatus.TryGetValue(id, out var status))
            {
                if (status)
                {
                    if (repo == null)
                    {
                        await ToastService.Error("传感器列表", "数据库未初始化");
                        return;
                    }

                    if (sensors == null || !sensors.Any(s => s.Id == id))
                    {
                        await ToastService.Error("传感器列表", "传感器不存在");
                        return;
                    }

                    var entity = sensors.Where(s => s.Id == id).FirstOrDefault();

                    var result = await repo.UpdateAsync(entity);
                    if (!result.Success)
                    {
                        await ToastService.Error($"传感器{entity.Name}", result.Message);
                        sensors = await repo.GetAll();
                        StateHasChanged();
                    }
                    else
                    {
                        await ToastService.Success($"传感器{entity.Name}", "数据更新成功");
                    }
                }

                changedStatus[id] = !status; // Toggle the status
            }
            else
            {
                changedStatus.TryAdd(id, false);
            }
        }

        [Inject]
        [NotNull]
        public NavigationManager? NavigationManager { get; set; }

        private Task OnComBack()
        {
            NavigationManager.NavigateTo("javascript:history.back()");
            return Task.CompletedTask;
        }
    }
}
